library(tidyverse) # for data cleaning and plotting
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.3 ✓ purrr 0.3.4
## ✓ tibble 3.1.2 ✓ dplyr 1.0.6
## ✓ tidyr 1.1.3 ✓ stringr 1.4.0
## ✓ readr 1.4.0 ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(lubridate) # for date manipulation
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
library(openintro) # for the abbr2state() function
## Loading required package: airports
## Loading required package: cherryblossom
## Loading required package: usdata
library(palmerpenguins)# for Palmer penguin data
library(maps) # for map data
##
## Attaching package: 'maps'
## The following object is masked from 'package:purrr':
##
## map
library(ggmap) # for mapping points on maps
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
library(gplots) # for col2hex() function
##
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
##
## lowess
library(RColorBrewer) # for color palettes
library(sf) # for working with spatial data
## Linking to GEOS 3.8.1, GDAL 3.1.4, PROJ 6.3.1
library(leaflet) # for highly customizable mapping
library(carData) # for Minneapolis police stops data
library(ggthemes) # for more themes (including theme_map())
theme_set(theme_minimal())
# Starbucks locations
Starbucks <- read_csv("https://www.macalester.edu/~ajohns24/Data/Starbucks.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## Brand = col_character(),
## `Store Number` = col_character(),
## `Store Name` = col_character(),
## `Ownership Type` = col_character(),
## `Street Address` = col_character(),
## City = col_character(),
## `State/Province` = col_character(),
## Country = col_character(),
## Postcode = col_character(),
## `Phone Number` = col_character(),
## Timezone = col_character(),
## Longitude = col_double(),
## Latitude = col_double()
## )
starbucks_us_by_state <- Starbucks %>%
filter(Country == "US") %>%
count(`State/Province`) %>%
mutate(state_name = str_to_lower(abbr2state(`State/Province`)))
# Lisa's favorite St. Paul places - example for you to create your own data
favorite_stp_by_lisa <- tibble(
place = c("Home", "Macalester College", "Adams Spanish Immersion",
"Spirit Gymnastics", "Bama & Bapa", "Now Bikes",
"Dance Spectrum", "Pizza Luce", "Brunson's"),
long = c(-93.1405743, -93.1712321, -93.1451796,
-93.1650563, -93.1542883, -93.1696608,
-93.1393172, -93.1524256, -93.0753863),
lat = c(44.950576, 44.9378965, 44.9237914,
44.9654609, 44.9295072, 44.9436813,
44.9399922, 44.9468848, 44.9700727)
)
#COVID-19 data from the New York Times
covid19 <- read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## date = col_date(format = ""),
## state = col_character(),
## fips = col_character(),
## cases = col_double(),
## deaths = col_double()
## )
If you were not able to get set up on GitHub last week, go here and get set up first. Then, do the following (if you get stuck on a step, don’t worry, I will help! You can always get started on the homework and we can figure out the GitHub piece later):
keep_md: TRUE in the YAML heading. The .md file is a markdown (NOT R Markdown) file that is an interim step to creating the html file. They are displayed fairly nicely in GitHub, so we want to keep it and look at it there. Click the boxes next to these two files, commit changes (remember to include a commit message), and push them (green up arrow).Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
These exercises will reiterate what you learned in the “Mapping data with R” tutorial. If you haven’t gone through the tutorial yet, you should do that first.
ggmap)Starbucks locations to a world map. Add an aesthetic to the world map that sets the color of the points according to the ownership type. What, if anything, can you deduce from this visualization?world <- get_stamenmap(
bbox = c(left = -180, bottom = -57, right = 179, top = 82.1),
maptype = "toner",
zoom = 2)
## Source : http://tile.stamen.com/toner/2/0/0.png
## Source : http://tile.stamen.com/toner/2/1/0.png
## Source : http://tile.stamen.com/toner/2/2/0.png
## Source : http://tile.stamen.com/toner/2/3/0.png
## Source : http://tile.stamen.com/toner/2/0/1.png
## Source : http://tile.stamen.com/toner/2/1/1.png
## Source : http://tile.stamen.com/toner/2/2/1.png
## Source : http://tile.stamen.com/toner/2/3/1.png
## Source : http://tile.stamen.com/toner/2/0/2.png
## Source : http://tile.stamen.com/toner/2/1/2.png
## Source : http://tile.stamen.com/toner/2/2/2.png
## Source : http://tile.stamen.com/toner/2/3/2.png
ggmap(world) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude, color = `Ownership Type`),
alpha = 0.3,
size = 0.1) +
theme_map() +
guides(colour = guide_legend(override.aes = list(size=5)))
## Warning: Removed 1 rows containing missing values (geom_point).
Overall, Starbucks seems to be most popular in the US, Japan, and the UK. This visualization tells us that the Starbucks in North America are primarily company owned and licensed. The Starbucks in Japan are primarily joint venture. The Starbucks in the UK are primarily franchise. There are other areas of consolidated types in other countries as well.
metro <- get_stamenmap(
bbox = c(left = -93.9, bottom = 44.7, right = -92.4, top = 45.3),
maptype = "toner-lite",
zoom = 10)
## Source : http://tile.stamen.com/toner-lite/10/244/367.png
## Source : http://tile.stamen.com/toner-lite/10/245/367.png
## Source : http://tile.stamen.com/toner-lite/10/246/367.png
## Source : http://tile.stamen.com/toner-lite/10/247/367.png
## Source : http://tile.stamen.com/toner-lite/10/248/367.png
## Source : http://tile.stamen.com/toner-lite/10/249/367.png
## Source : http://tile.stamen.com/toner-lite/10/244/368.png
## Source : http://tile.stamen.com/toner-lite/10/245/368.png
## Source : http://tile.stamen.com/toner-lite/10/246/368.png
## Source : http://tile.stamen.com/toner-lite/10/247/368.png
## Source : http://tile.stamen.com/toner-lite/10/248/368.png
## Source : http://tile.stamen.com/toner-lite/10/249/368.png
## Source : http://tile.stamen.com/toner-lite/10/244/369.png
## Source : http://tile.stamen.com/toner-lite/10/245/369.png
## Source : http://tile.stamen.com/toner-lite/10/246/369.png
## Source : http://tile.stamen.com/toner-lite/10/247/369.png
## Source : http://tile.stamen.com/toner-lite/10/248/369.png
## Source : http://tile.stamen.com/toner-lite/10/249/369.png
ggmap(metro) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude, color = `Ownership Type`),
size = 1.5) +
theme_map()
## Warning: Removed 25450 rows containing missing values (geom_point).
Bigger numbers of zoom give more details while smaller numbers make the map be less detailed. For example, in the last map if I change the zoom to 7, the only city names visible are Minneapolis, St. Paul, and Bloomington.
get_stamenmap() in help and look at maptype). Include a map with one of the other map types.metro2 <- get_stamenmap(
bbox = c(left = -93.9, bottom = 44.7, right = -92.4, top = 45.3),
maptype = "watercolor",
zoom = 10)
## Source : http://tile.stamen.com/watercolor/10/244/367.jpg
## Source : http://tile.stamen.com/watercolor/10/245/367.jpg
## Source : http://tile.stamen.com/watercolor/10/246/367.jpg
## Source : http://tile.stamen.com/watercolor/10/247/367.jpg
## Source : http://tile.stamen.com/watercolor/10/248/367.jpg
## Source : http://tile.stamen.com/watercolor/10/249/367.jpg
## Source : http://tile.stamen.com/watercolor/10/244/368.jpg
## Source : http://tile.stamen.com/watercolor/10/245/368.jpg
## Source : http://tile.stamen.com/watercolor/10/246/368.jpg
## Source : http://tile.stamen.com/watercolor/10/247/368.jpg
## Source : http://tile.stamen.com/watercolor/10/248/368.jpg
## Source : http://tile.stamen.com/watercolor/10/249/368.jpg
## Source : http://tile.stamen.com/watercolor/10/244/369.jpg
## Source : http://tile.stamen.com/watercolor/10/245/369.jpg
## Source : http://tile.stamen.com/watercolor/10/246/369.jpg
## Source : http://tile.stamen.com/watercolor/10/247/369.jpg
## Source : http://tile.stamen.com/watercolor/10/248/369.jpg
## Source : http://tile.stamen.com/watercolor/10/249/369.jpg
ggmap(metro2) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude),
size = 1.5) +
theme_map()
## Warning: Removed 25450 rows containing missing values (geom_point).
annotate() function (see ggplot2 cheatsheet).ggmap(metro) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude),
size = 1.5) +
annotate("text", y = 44.925, x = -93.1691, label = "Macalester", color ="red", size = 3) +
annotate("point", y = 44.9379, x = -93.1691, color = "red") +
theme_map()
## Warning: Removed 25450 rows containing missing values (geom_point).
geom_map())The example I showed in the tutorial did not account for population of each state in the map. In the code below, a new variable is created, starbucks_per_10000, that gives the number of Starbucks per 10,000 people. It is in the starbucks_with_2018_pop_est dataset.
census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## state = col_character(),
## est_pop_2018 = col_double()
## )
starbucks_with_2018_pop_est <-
starbucks_us_by_state %>%
left_join(census_pop_est_2018,
by = c("state_name" = "state")) %>%
mutate(starbucks_per_10000 = (n/est_pop_2018)*10000)
dplyr review: Look through the code above and describe what each line of code does.167 reads in a csv file and assigns it to be “census_pop_est_2018” 168 separates the column “state” into two columns, called “dot” and “state”, splitting by any non-alphanumeric characters. “extra” makes it so that if there are too many pieces from the separation, it will only be split twice. 169 removes the “dot” column from the table by selecting all columns except that one. 170 replaces the “state” column with the old state column, but all lower-case letters. 174 joins the two tables census_pop_est_2018 and starbucks_us_by_state by making state_name equal to state. It is a left join, so it will keep all cases in starbucks_us_by_state. 176 creates a new column, starbucks_per_10000, which divides n by the estimated population of the state in 2018 and multiplies that by 10000.
states_map <- map_data("state")
starbucks_with_2018_pop_est %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state_name,
fill = starbucks_per_10000)) +
geom_point(data = Starbucks %>% filter(`Country` == "US", `State/Province` != "HI", `State/Province` != "AK"),
aes(x = Longitude, y = Latitude),
size = .05,
alpha = .2,
color = "goldenrod") +
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map() +
labs(title = "Starbucks in U.S.", fill = "Starbucks per 10,000 People", caption = "Plot by Ingrid O'Connor") +
theme(legend.background = element_blank(), legend.position = "right")
Although there are a lot of Starbucks in the northeast, it also must be more populated than states on the West coast, which seem to have a similar amomunt of Starbucks, but are much lighter in color (more Starbucks per 10,000 people).
leaflet)tibble() function that has 10-15 rows of your favorite places. The columns will be the name of the location, the latitude, the longitude, and a column that indicates if it is in your top 3 favorite locations or not. For an example of how to use tibble(), look at the favorite_stp_by_lisa I created in the data R code chunk at the beginning.favorites_ingrid <- tibble(
place = c("Home", "Macalester College", "Cam Ranh Bay Restaurant", "Subway", "My Cabin", "Black Sheep Pizza", "Theodore Wirth Park", "Giant's Ridge", "Minnehaha Falls", "University of Minnesota"),
long = c(-93.346580, -93.1712321, -93.291980, -93.354020, -91.909092, -93.275688, -93.321327, -92.303300, -93.210983, -93.233118),
lat = c(44.733210, 44.9378965, 44.746650, 44.746700, 47.371596, 44.987309, 44.992489, 47.575710, 44.915274, 44.976160),
favorite = c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE)
)
leaflet map that uses circles to indicate your favorite places. Label them with the name of the place. Choose the base map you like best. Color your 3 favorite places differently than the ones that are not in your top 3 (HINT: colorFactor()). Add a legend that explains what the colors mean.pal2 <- colorFactor(c("red","blue"),
domain = favorites_ingrid$favorite)
leaflet(favorites_ingrid) %>%
addTiles() %>%
addCircles(
popup = ~paste(place),
opacity = 1,
color = ~pal2(favorite)
) %>%
addLegend(pal = pal2,
values = ~favorite,
title = "Top 3 Favorite?",
position = "bottomright")
## Assuming "long" and "lat" are longitude and latitude, respectively
# Order of when I first visited
favorites_ingrid <- tibble(
place = c("Home", "My Cabin", "Minnehaha Falls", "University of Minnesota", "Cam Ranh Bay Restaurant", "Subway", "Black Sheep Pizza", "Theodore Wirth Park", "Giant's Ridge", "Macalester College"),
long = c(-93.346580, -91.909092, -93.210983, -93.233118, -93.291980, -93.354020, -93.275688, -93.321327, -92.303300, -93.1712321),
lat = c(44.733210, 47.371596, 44.915274, 44.976160, 44.746650, 44.746700, 44.987309, 44.992489, 47.575710, 44.9378965),
favorite = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE)
)
leaflet(favorites_ingrid) %>%
addTiles() %>%
addCircles(
popup = ~paste(place),
opacity = 1,
color = ~pal2(favorite)
) %>%
addLegend(pal = pal2,
values = ~favorite,
title = "Top 3 Favorite?",
position = "bottomright") %>%
addPolylines(lng = ~long,
lat = ~lat,
color = col2hex("darkred"))
## Assuming "long" and "lat" are longitude and latitude, respectively
favorites_ingrid %>%
mutate(twin_cities = c(TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE))
This section will revisit some datasets we have used previously and bring in a mapping component.
The data come from Washington, DC and cover the last quarter of 2014.
Two data tables are available:
Trips contains records of individual rentalsStations gives the locations of the bike rental stationsHere is the code to read in the data. We do this a little differently than usualy, which is why it is included here rather than at the top of this file. To avoid repeatedly re-reading the files, start the data import chunk with {r cache = TRUE} rather than the usual {r}. This code reads in the large dataset right away.
data_site <-
"https://www.macalester.edu/~dshuman1/data/112/2014-Q4-Trips-History-Data.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations<-read_csv("http://www.macalester.edu/~dshuman1/data/112/DC-Stations.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## name = col_character(),
## lat = col_double(),
## long = col_double(),
## nbBikes = col_double(),
## nbEmptyDocks = col_double()
## )
Stations to make a visualization of the total number of departures from each station in the Trips data. Use either color or size to show the variation in number of departures. This time, plot the points on top of a map. Use any of the mapping tools you’d like.dc <- get_stamenmap(
bbox = c(left = -77.3490, top = 39.1234, bottom = 38.7886, right = -76.6005),
maptype = "terrain",
zoom = 11
)
## Source : http://tile.stamen.com/terrain/11/583/781.png
## Source : http://tile.stamen.com/terrain/11/584/781.png
## Source : http://tile.stamen.com/terrain/11/585/781.png
## Source : http://tile.stamen.com/terrain/11/586/781.png
## Source : http://tile.stamen.com/terrain/11/587/781.png
## Source : http://tile.stamen.com/terrain/11/588/781.png
## Source : http://tile.stamen.com/terrain/11/583/782.png
## Source : http://tile.stamen.com/terrain/11/584/782.png
## Source : http://tile.stamen.com/terrain/11/585/782.png
## Source : http://tile.stamen.com/terrain/11/586/782.png
## Source : http://tile.stamen.com/terrain/11/587/782.png
## Source : http://tile.stamen.com/terrain/11/588/782.png
## Source : http://tile.stamen.com/terrain/11/583/783.png
## Source : http://tile.stamen.com/terrain/11/584/783.png
## Source : http://tile.stamen.com/terrain/11/585/783.png
## Source : http://tile.stamen.com/terrain/11/586/783.png
## Source : http://tile.stamen.com/terrain/11/587/783.png
## Source : http://tile.stamen.com/terrain/11/588/783.png
## Source : http://tile.stamen.com/terrain/11/583/784.png
## Source : http://tile.stamen.com/terrain/11/584/784.png
## Source : http://tile.stamen.com/terrain/11/585/784.png
## Source : http://tile.stamen.com/terrain/11/586/784.png
## Source : http://tile.stamen.com/terrain/11/587/784.png
## Source : http://tile.stamen.com/terrain/11/588/784.png
stations2 <- Trips %>%
group_by(sstation) %>%
summarize(number_of_departures = n()) %>%
inner_join(Stations, by = c("sstation" = "name"))
ggmap(dc) +
geom_point(data = stations2,
aes(x = long, y = lat, color = number_of_departures),
size = 1,
alpha = 1) +
scale_color_viridis_c(option = "plasma") +
theme_map() +
labs(color = "Number of Departures", title = "Washington D.C. Bike Rental Stations (last quarter of 2014)")
## Warning: Removed 1 rows containing missing values (geom_point).
stations3 <- Trips %>%
mutate(client_casual = (client == "Casual")) %>%
group_by(sstation) %>%
summarize(total_departures = n(), casual_departures = sum(client_casual)) %>%
mutate(percent_casual = casual_departures / total_departures) %>%
inner_join(Stations, by = c("sstation" = "name"))
ggmap(dc) +
geom_point(data = stations3,
aes(x = long, y = lat, color = percent_casual),
size = 1,
alpha = 1) +
scale_color_viridis_c(option = "plasma") +
theme_map() +
labs(color = "Percent of Casual Clients", title = "Washington D.C. Bike Rental Stations (last quarter of 2014)") +
theme(legend.position = "right")
## Warning: Removed 1 rows containing missing values (geom_point).
Many of the stations with a high percentage of casual clients are along the river and in the center of the city, most likely at tourist sites.
The following exercises will use the COVID-19 data from the NYT.
Create a map that colors the states by the most recent cumulative number of COVID-19 cases (remember, these data report cumulative numbers so you don’t need to compute that). Describe what you see. What is the problem with this map?
Now add the population of each state to the dataset and color the states by most recent cumulative cases/10,000 people. See the code for doing this with the Starbucks data. You will need to make some modifications.
CHALLENGE Choose 4 dates spread over the time period of the data and create the same map as in exercise 12 for each of the dates. Display the four graphs together using faceting. What do you notice?
These exercises use the datasets MplsStops and MplsDemo from the carData library. Search for them in Help to find out more information.
Use the MplsStops dataset to find out how many stops there were for each neighborhood and the proportion of stops that were for a suspicious vehicle or person. Sort the results from most to least number of stops. Save this as a dataset called mpls_suspicious and display the table.
Use a leaflet map and the MplsStops dataset to display each of the stops on a map as a small point. Color the points differently depending on whether they were for suspicious vehicle/person or a traffic stop (the problem variable). HINTS: use addCircleMarkers, set stroke = FAlSE, use colorFactor() to create a palette.
Save the folder from moodle called Minneapolis_Neighborhoods into your project/repository folder for this assignment. Make sure the folder is called Minneapolis_Neighborhoods. Use the code below to read in the data and make sure to delete the eval=FALSE. Although it looks like it only links to the .sph file, you need the entire folder of files to create the mpls_nbhd data set. These data contain information about the geometries of the Minneapolis neighborhoods. Using the mpls_nbhd dataset as the base file, join the mpls_suspicious and MplsDemo datasets to it by neighborhood (careful, they are named different things in the different files). Call this new dataset mpls_all.
mpls_nbhd <- st_read("Minneapolis_Neighborhoods/Minneapolis_Neighborhoods.shp", quiet = TRUE)
Use leaflet to create a map from the mpls_all data that colors the neighborhoods by prop_suspicious. Display the neighborhood name as you scroll over it. Describe what you observe in the map.
Use leaflet to create a map of your own choosing. Come up with a question you want to try to answer and use the map to help answer that question. Describe what your map shows.
DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?